package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"sync"

	"video/global"
	menuServer "video/menu-server"
	"video/pkg"

	"github.com/gin-gonic/gin"
)

func main() {

	gin.SetMode(gin.ReleaseMode)

	global.VideoPathList = pkg.ReadDir("./videos/*", global.GROUP_LEN)
	global.PortPool = &pkg.PortPool{BasePort: 9011}
	global.PortPool.Fill(len(global.VideoPathList))

	if videoServerPool, err := pkg.NewSubServerPool(global.VideoPathList, global.PortPool); err != nil {
		log.Fatal(err)
	} else {
		global.VideoServerPool = videoServerPool
	}

	for _, item := range global.VideoServerPool.Pool {
		(*item.Service).GET("/", HomeHandler)
		item.Service.GET("/video/:id", ViedeoHandler)
	}

	m := menuServer.CreateMenuerver(9010)

	wg := &sync.WaitGroup{}

	global.VideoServerPool.Run(wg)
	m.Run(wg)

	wg.Wait()

}

func HomeHandler(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"msg": "home page"})
}

func ViedeoHandler(c *gin.Context) {

	var server *pkg.Server

	if s, exists := c.Get("server"); exists {
		var ok bool
		server, ok = s.(*pkg.Server)

		if !ok {
			log.Fatal("not funed Server")
		}
	}

	id, err := strconv.Atoi(c.Param("id"))

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"msg": err})
		return
	}

	if id >= server.Len() {
		c.JSON(http.StatusInternalServerError, gin.H{"msg": fmt.Sprintf("未找到视频: %d", id)})
		return
	}

	videoPath := server.VideoPathList[id]

	video, err := ioutil.ReadFile(videoPath)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"msg": err})
		return
	}

	c.Header("Content-Type", "video/mp4")

	_, err = c.Writer.Write(video)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"msg": err})
		return
	}

}
